package com.desmart.renjiao.login;

import android.util.Log;

import com.desmart.renjiao.App;
import com.desmart.renjiao.bean.LoginBean;
import com.lemon.library.constants.PreferencesConstants;
import com.desmart.renjiao.xmlparase.ResultXmlUtils;
import com.google.gson.Gson;
import com.lemon.library.net.rx.RxObservableListener;
import com.lemon.library.utils.PreferencesUtils;
import com.lemon.library.utils.ToastUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class LoginP extends Login.LoginP {

    @Override
    void login(String name, String password) {

        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                "xmlns:ser=\"http://services.destram.cn.com/\"><soapenv:Header/><soapenv:Body><ser:GetUserInfo><arg0>" +
                name +
                "</arg0><arg1>" + password +
                "</arg1></ser:GetUserInfo></soapenv:Body></soapenv:Envelope>";

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), xml);
        getRxManager().addObserver(mModel.login(body), new RxObservableListener<ResponseBody>(mView) {
            @Override
            public void onNext(ResponseBody responseBody) {
                super.onNext(responseBody);

                String ss = null;
                try {
                    ss = responseBody.string();
                    InputStream inputStream = new ByteArrayInputStream(ss.getBytes("UTF-8"));
                    String loginResult = ResultXmlUtils.readXML(inputStream);
                    LoginBean loginBean = new Gson().fromJson(loginResult, LoginBean.class);
                    if ("200".equals(loginBean.getCode())) {
                        App.setUserName(name);
                        PreferencesUtils.putString(PreferencesConstants.login_username, name);
                        PreferencesUtils.putString(PreferencesConstants.login_password, password);
                        PreferencesUtils.putString(PreferencesConstants.login_info, loginResult);
                        PreferencesUtils.putString(PreferencesConstants.login_Token, loginBean.getLtpaToken());
                        PreferencesUtils.putLong(PreferencesConstants.login_Token_save_time,System.currentTimeMillis());
                        mView.onLoginSuccess();
                    } else {
                        ToastUtils.showGravity(loginBean.getMassage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


}
